home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / shutil.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  8.4 KB  |  271 lines

  1. """Utility functions for copying files and directory trees.
  2.  
  3. XXX The functions here don't copy the resource fork or other metadata on Mac.
  4.  
  5. """
  6.  
  7. import os
  8. import sys
  9. import stat
  10. from os.path import abspath
  11. import fnmatch
  12. import errno
  13.  
  14. __all__ = ["copyfileobj","copyfile","copymode","copystat","copy","copy2",
  15.            "copytree","move","rmtree","Error"]
  16.  
  17. class Error(EnvironmentError):
  18.     pass
  19.  
  20. try:
  21.     WindowsError
  22. except NameError:
  23.     WindowsError = None
  24.  
  25. def copyfileobj(fsrc, fdst, length=16*1024):
  26.     """copy data from file-like object fsrc to file-like object fdst"""
  27.     while 1:
  28.         buf = fsrc.read(length)
  29.         if not buf:
  30.             break
  31.         fdst.write(buf)
  32.  
  33. def _samefile(src, dst):
  34.     # Macintosh, Unix.
  35.     if hasattr(os.path,'samefile'):
  36.         try:
  37.             return os.path.samefile(src, dst)
  38.         except OSError:
  39.             return False
  40.  
  41.     # All other platforms: check for same pathname.
  42.     return (os.path.normcase(os.path.abspath(src)) ==
  43.             os.path.normcase(os.path.abspath(dst)))
  44.  
  45. def copyfile(src, dst):
  46.     """Copy data from src to dst"""
  47.     if _samefile(src, dst):
  48.         raise Error("`%s` and `%s` are the same file" % (src, dst))
  49.  
  50.     with open(src, 'rb') as fsrc:
  51.         with open(dst, 'wb') as fdst:
  52.             copyfileobj(fsrc, fdst)
  53.  
  54. def copymode(src, dst):
  55.     """Copy mode bits from src to dst"""
  56.     if hasattr(os, 'chmod'):
  57.         st = os.stat(src)
  58.         mode = stat.S_IMODE(st.st_mode)
  59.         os.chmod(dst, mode)
  60.  
  61. def copystat(src, dst):
  62.     """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
  63.     st = os.stat(src)
  64.     mode = stat.S_IMODE(st.st_mode)
  65.     if hasattr(os, 'utime'):
  66.         os.utime(dst, (st.st_atime, st.st_mtime))
  67.     if hasattr(os, 'chmod'):
  68.         os.chmod(dst, mode)
  69.     if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
  70.         try:
  71.             os.chflags(dst, st.st_flags)
  72.         except OSError, why:
  73.             if not hasattr(errno, 'EOPNOTSUPP') or why.errno != errno.EOPNOTSUPP:
  74.                 raise
  75.  
  76. def copy(src, dst):
  77.     """Copy data and mode bits ("cp src dst").
  78.  
  79.     The destination may be a directory.
  80.  
  81.     """
  82.     if os.path.isdir(dst):
  83.         dst = os.path.join(dst, os.path.basename(src))
  84.     copyfile(src, dst)
  85.     copymode(src, dst)
  86.  
  87. def copy2(src, dst):
  88.     """Copy data and all stat info ("cp -p src dst").
  89.  
  90.     The destination may be a directory.
  91.  
  92.     """
  93.     if os.path.isdir(dst):
  94.         dst = os.path.join(dst, os.path.basename(src))
  95.     copyfile(src, dst)
  96.     copystat(src, dst)
  97.  
  98. def ignore_patterns(*patterns):
  99.     """Function that can be used as copytree() ignore parameter.
  100.  
  101.     Patterns is a sequence of glob-style patterns
  102.     that are used to exclude files"""
  103.     def _ignore_patterns(path, names):
  104.         ignored_names = []
  105.         for pattern in patterns:
  106.             ignored_names.extend(fnmatch.filter(names, pattern))
  107.         return set(ignored_names)
  108.     return _ignore_patterns
  109.  
  110. def copytree(src, dst, symlinks=False, ignore=None):
  111.     """Recursively copy a directory tree using copy2().
  112.  
  113.     The destination directory must not already exist.
  114.     If exception(s) occur, an Error is raised with a list of reasons.
  115.  
  116.     If the optional symlinks flag is true, symbolic links in the
  117.     source tree result in symbolic links in the destination tree; if
  118.     it is false, the contents of the files pointed to by symbolic
  119.     links are copied.
  120.  
  121.     The optional ignore argument is a callable. If given, it
  122.     is called with the `src` parameter, which is the directory
  123.     being visited by copytree(), and `names` which is the list of
  124.     `src` contents, as returned by os.listdir():
  125.  
  126.         callable(src, names) -> ignored_names
  127.  
  128.     Since copytree() is called recursively, the callable will be
  129.     called once for each directory that is copied. It returns a
  130.     list of names relative to the `src` directory that should
  131.     not be copied.
  132.  
  133.     XXX Consider this example code rather than the ultimate tool.
  134.  
  135.     """
  136.     names = os.listdir(src)
  137.     if ignore is not None:
  138.         ignored_names = ignore(src, names)
  139.     else:
  140.         ignored_names = set()
  141.  
  142.     os.makedirs(dst)
  143.     errors = []
  144.     for name in names:
  145.         if name in ignored_names:
  146.             continue
  147.         srcname = os.path.join(src, name)
  148.         dstname = os.path.join(dst, name)
  149.         try:
  150.             if symlinks and os.path.islink(srcname):
  151.                 linkto = os.readlink(srcname)
  152.                 os.symlink(linkto, dstname)
  153.             elif os.path.isdir(srcname):
  154.                 copytree(srcname, dstname, symlinks, ignore)
  155.             else:
  156.                 copy2(srcname, dstname)
  157.             # XXX What about devices, sockets etc.?
  158.         except (IOError, os.error), why:
  159.             errors.append((srcname, dstname, str(why)))
  160.         # catch the Error from the recursive copytree so that we can
  161.         # continue with other files
  162.         except Error, err:
  163.             errors.extend(err.args[0])
  164.     try:
  165.         copystat(src, dst)
  166.     except OSError, why:
  167.         if WindowsError is not None and isinstance(why, WindowsError):
  168.             # Copying file access times may fail on Windows
  169.             pass
  170.         else:
  171.             errors.extend((src, dst, str(why)))
  172.     if errors:
  173.         raise Error, errors
  174.  
  175. def rmtree(path, ignore_errors=False, onerror=None):
  176.     """Recursively delete a directory tree.
  177.  
  178.     If ignore_errors is set, errors are ignored; otherwise, if onerror
  179.     is set, it is called to handle the error with arguments (func,
  180.     path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
  181.     path is the argument to that function that caused it to fail; and
  182.     exc_info is a tuple returned by sys.exc_info().  If ignore_errors
  183.     is false and onerror is None, an exception is raised.
  184.  
  185.     """
  186.     if ignore_errors:
  187.         def onerror(*args):
  188.             pass
  189.     elif onerror is None:
  190.         def onerror(*args):
  191.             raise
  192.     try:
  193.         if os.path.islink(path):
  194.             # symlinks to directories are forbidden, see bug #1669
  195.             raise OSError("Cannot call rmtree on a symbolic link")
  196.     except OSError:
  197.         onerror(os.path.islink, path, sys.exc_info())
  198.         # can't continue even if onerror hook returns
  199.         return
  200.     names = []
  201.     try:
  202.         names = os.listdir(path)
  203.     except os.error, err:
  204.         onerror(os.listdir, path, sys.exc_info())
  205.     for name in names:
  206.         fullname = os.path.join(path, name)
  207.         try:
  208.             mode = os.lstat(fullname).st_mode
  209.         except os.error:
  210.             mode = 0
  211.         if stat.S_ISDIR(mode):
  212.             rmtree(fullname, ignore_errors, onerror)
  213.         else:
  214.             try:
  215.                 os.remove(fullname)
  216.             except os.error, err:
  217.                 onerror(os.remove, fullname, sys.exc_info())
  218.     try:
  219.         os.rmdir(path)
  220.     except os.error:
  221.         onerror(os.rmdir, path, sys.exc_info())
  222.  
  223.  
  224. def _basename(path):
  225.     # A basename() variant which first strips the trailing slash, if present.
  226.     # Thus we always get the last component of the path, even for directories.
  227.     return os.path.basename(path.rstrip(os.path.sep))
  228.  
  229. def move(src, dst):
  230.     """Recursively move a file or directory to another location. This is
  231.     similar to the Unix "mv" command.
  232.  
  233.     If the destination is a directory or a symlink to a directory, the source
  234.     is moved inside the directory. The destination path must not already
  235.     exist.
  236.  
  237.     If the destination already exists but is not a directory, it may be
  238.     overwritten depending on os.rename() semantics.
  239.  
  240.     If the destination is on our current filesystem, then rename() is used.
  241.     Otherwise, src is copied to the destination and then removed.
  242.     A lot more could be done here...  A look at a mv.c shows a lot of
  243.     the issues this implementation glosses over.
  244.  
  245.     """
  246.     real_dst = dst
  247.     if os.path.isdir(dst):
  248.         real_dst = os.path.join(dst, _basename(src))
  249.         if os.path.exists(real_dst):
  250.             raise Error, "Destination path '%s' already exists" % real_dst
  251.     try:
  252.         os.rename(src, real_dst)
  253.     except OSError:
  254.         if os.path.isdir(src):
  255.             if destinsrc(src, dst):
  256.                 raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
  257.             copytree(src, real_dst, symlinks=True)
  258.             rmtree(src)
  259.         else:
  260.             copy2(src, real_dst)
  261.             os.unlink(src)
  262.  
  263. def destinsrc(src, dst):
  264.     src = abspath(src)
  265.     dst = abspath(dst)
  266.     if not src.endswith(os.path.sep):
  267.         src += os.path.sep
  268.     if not dst.endswith(os.path.sep):
  269.         dst += os.path.sep
  270.     return dst.startswith(src)
  271.